package com.andy.qi.conf;

import java.security.Principal;

import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptorAdapter;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;

//@Configuration
//@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        //这行代码是配置中间人的 url  一会儿服务器会将产生的信息发送到这个地址,由订阅该地址的websocket客户端消费掉。<span style="white-space:pre">    </span>
        config.enableSimpleBroker( "/topic" );
        config.setApplicationDestinationPrefixes( "/app" );
    }
    
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        //这个方法是产生了一个endpoint,参数为websocket的客户端要对服务器端进行连接的地址
        registry.addEndpoint( "/gs-guide-websocket" ).withSockJS();
    }
    
    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.setInterceptors(new ChannelInterceptorAdapter() {
            
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                
                StompHeaderAccessor accessor =
                        MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
                
                if (StompCommand.CONNECT.equals(accessor.getCommand())) {
                    Principal user = null ; // TODO access authentication header(s)
                    accessor.setUser(user);
                }
                
                return message;
            }
        });
    }
    


}